//
//  MJRefreshAutoImageFooter.m
//  MJRefreshExample
//  图片转圈圈
//  Copyright (c) 2016年 土哥. All rights reserved.
//

#import "MJRefreshAutoImageFooter.h"

@interface MJRefreshAutoImageFooter()
{
    __unsafe_unretained UIImageView *_arrowView;
}
@end

@implementation MJRefreshAutoImageFooter
#pragma mark - 懒加载子控件
- (UIImageView *)arrowView
{
    if (!_arrowView) {
//edit by zxl 20170801
//        UIImage *image = [UIImage imageNamed:MJRefreshSrcName(@"jkt_logo.png")] ?: [UIImage imageNamed:MJRefreshFrameworkSrcName(@"jkt_logo.png")];
        UIImage *image = [UIImage imageNamed:@"jkt_logo"];
//end
        UIImageView *arrowView = [[UIImageView alloc] initWithImage:image];
        [self addSubview:_arrowView = arrowView];
        self.arrowView.alpha = 0;
    }
    return _arrowView;
}

#pragma makr - 重写父类的方法
- (void)prepare
{
    [super prepare];
}

- (void)placeSubviews
{
    [super placeSubviews];
    
    // 箭头的中心点
    CGFloat arrowCenterX = self.mj_w * 0.5;
    CGFloat arrowCenterY = self.mj_h * 0.5;
    CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY);
    
    // 箭头
    if (self.arrowView.constraints.count == 0) {
        self.arrowView.mj_size = self.arrowView.image.size;
        self.arrowView.center = arrowCenter;
    }
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState
    
    // 根据状态做事情
    if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
        [self stopAnimating];
    } else if (state == MJRefreshStateRefreshing) {
        [self startAnimating];
    } else if (state == MJRefreshStateWillRefresh) {
        [self startAnimating];
    }
}


-(void)startAnimating
{
    self.arrowView.hidden=NO;
    [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
        self.stateLabel.alpha = 0;
        self.arrowView.alpha = 0.5;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
            self.arrowView.alpha = 1;
        }];
        CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI * 2.0 ];
        rotationAnimation.duration = MJRefreshSlowAnimationDuration*2;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = INT16_MAX;
        [_arrowView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    }];
}

-(void)stopAnimating
{
    [self.arrowView.layer removeAllAnimations];
    [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
        self.arrowView.transform = CGAffineTransformIdentity;
        self.arrowView.alpha = 0;
        self.stateLabel.alpha = 1;
    } completion:^(BOOL finished) {
        if (finished) {
            self.arrowView.hidden=YES;
        }
    }];
}

@end
